package com.oj.controller;

import com.oj.common.ProblemNotFoundException;
import com.oj.entity.R;
import com.oj.common.Uitls;
import com.oj.compile.Answer;
import com.oj.compile.Question;
import com.oj.compile.Task;
import com.oj.entity.CompileRequest;
import com.oj.entity.Problem;
import com.oj.service.ProblemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/compile")
@Api(tags = "代码编译运行接口")
public class CompileController {


    @Autowired
    private ProblemService problemService;
    @Autowired
    private Task task;


    @ApiOperation(value = "编译运行代码", notes = "根据题目id和用户提交的代码编译运行")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "题目id", required = true, dataType = "Integer", paramType = "path"),
            @ApiImplicitParam(name = "compileRequest", value = "用户提交的代码", required = true, dataType = "CompileRequest", paramType = "body")
    })
    @PostMapping(value = "/{id}")
    @ResponseBody
    public R<Answer> compile(@PathVariable(value = "id") Integer id, @RequestBody CompileRequest compileRequest) {
        try {
            log.info("收到用户提交的代码：id: {} ",id);
            //1.根据id在数据库里查题目信息和测试用例代码
            Problem problem = problemService.selectProblemById(id);
            String testCode = problem.getTestCode();
            String requestCode = compileRequest.getCode();

            //2、合并成完整代码
            String finalCode = Uitls.mergeCode(testCode, requestCode);
            Question question = new Question();
            question.setCode(finalCode);

            //3.调用task 编译运行
            Answer answer = task.compileAndRun(question);

            //4.返回结果
            return R.success(answer);
        } catch (ProblemNotFoundException e) {
            //5.捕获ProblemNotFoundException异常并使用log.error()方法记录异常信息
            log.error("题目未找到");
            log.error("编译运行出现异常：{}", e.getMessage());
            return R.error("题目未找到：" + e.getMessage());
        } catch (Exception e) {
            //6.捕获异常并使用log.error()方法记录异常信息
            log.error("编译运行出现异常：{}", e.getMessage());
            //7.返回错误信息
            return R.error("编译运行出现异常：" + e.getMessage());
        }
    }
}


